<?php

namespace app\admin\controller;

use app\common\controller\Backend;

class User extends Backend
{
    public $navTitle = "user";
    public function __construct()
    {
        parent::__construct();

        $this->UserModel = model('User.User');

        $this->Region = model('Region');
    }

    public function index()
    {

        $userList = $this->UserModel->with(['provinces'])->paginate(10);

        if ($this->request->isGet()) {
            $search_field = $this->request->param('search_field', '');
            $keyword = $this->request->param('keyword', '');

            if ($keyword == '') $userList = $this->UserModel->with(['provinces'])->paginate(10);

            if ($search_field == 'nickname') {
                $userList = $this->UserModel
                    ->with(['provinces'])
                    ->where('nickname', 'like', "%{$keyword}%")
                    ->paginate(10);
            }

            if ($search_field == 'email') {
                $userList = $this->UserModel
                    ->with(['provinces'])
                    ->where('email', 'like', "%{$keyword}%")
                    ->paginate(10);
            }
        }

        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'userList' => $userList,
        ]);
    }

    public function edit()
    {
        $userid = $this->request->param('id');

        $user = $this->UserModel->find($userid);

        if ($this->request->isPost()) {

            $action = $this->request->param('action', '');
            // halt($action);
            if ($action == 'repass') {
                $formData = $this->request->param();

                // if (!captcha_check($formData['vercode'])) $this->error('验证码错误');

                if ($formData['newpass'] != $formData['repass']) $this->error('新密码和确认密码不一致');

                $salt = build_ranstr();

                $password = md5($formData['newpass'] . $salt);

                $data = [
                    'id' => $userid,
                    'password' => $password,
                    'salt' => $salt,
                ];

                $result = $this->UserModel->isUpdate()->save($data);

                if ($result === FALSE) {
                    $this->error('密码重置失败');
                } else {
                    $this->success('密码重置成功');
                }
            }

            if ($action == 'avatar') {
                // halt();
                $avatar = upload('avatar');

                if ($avatar['code'] == 0) $this->error('上传失败，' . $avatar['msg']);

                $data = [
                    'id' => $userid,
                    'avatar' => $avatar['data']
                ];

                $result = $this->UserModel->isUpdate()->save($data);

                if ($result === FALSE) {
                    @is_file('.' . $data['avatar']) && unlink('.' . $user['avatar']);
                    $this->error('更新头像失败');
                } else {
                    @is_file('.' . $user['avatar'] && '.' . $user['avatar']);
                    $this->success('更新头像成功');
                }
            }

            if ($action == 'cover') {
                // halt();
                $cover = upload('cover');

                if ($cover['code'] == 0) $this->error('上传失败，' . $cover['msg']);

                $data = [
                    'id' => $userid,
                    'cover' => $cover['data']
                ];

                $result = $this->UserModel->isUpdate()->save($data);

                if ($result === FALSE) {
                    @is_file('.' . $data['cover']) && unlink('.' . $user['cover']);
                    $this->error('更新背景失败');
                } else {
                    @is_file('.' . $user['cover'] && '.' . $user['cover']);
                    $this->success('更新背景成功');
                }
            }
        }


        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'user' => $user,
        ]);
    }

    public function info()
    {
        $type = $this->request->get('type', 'info');

        $userid = $this->request->param('id', '');

        $user = model('User.User')->find($userid);

        $commentList = model('Post.Comment')
            ->with('post')
            ->where(['comment.userid' => $userid])
            ->paginate(10, false, [
                'var_page' => 'cpage',
                'query' => ['type' => 'comment']
            ]);

        $recordList = model('User.Record')
            ->with(['user'])
            ->where(['userid' => $userid])
            ->order('createtime', 'desc')
            ->paginate(10, false, [
                'var_page' => 'rpage',
                'query' => ['type' => 'message']
            ]);

        // halt($recoed);

        return $this->fetch('', [
            'user' => $user,
            'navTitle' => $this->navTitle,
            'recordList' => $recordList,
            'commentList' => $commentList,
            'type' => $type
        ]);
    }

    public function delete()
    {
        if ($this->request->isAjax()) {
            $action = $this->request->param('action', '');

            if ($action == 'del') {
                $userid = $this->request->param('userid', '');

                $user = $this->UserModel->find($userid);

                if (!$user) $this->error('用户不存在');

                $result = $this->UserModel->destroy($userid);

                if ($result === FALSE) {
                    $this->error('删除失败');
                } else {
                    @is_file('.' . $user['avatar']) && unlink('.' . $user['avatar']);
                    $this->success('删除成功', url('admin/user/index'));
                }
            }

            if ($action == 'dels') {
                // TODO 接收所有数据
                $formData = $this->request->param();
                // TODO 转存idArr
                $idArr = $formData['idArr'];

                $result = $this->UserModel->destroy($idArr);

                if ($result === FALSE) {
                    $this->error('删除失败');
                } else {
                    $this->success('删除成功', url('admin/user/index'));
                }
            }
        }
    }

    public function appman()
    {
        if ($this->request->isAjax()) {
            $action = $this->request->param('action', '');

            // TODO 接收数据
            $formData = $this->request->param();

            // TODO 还原
            if ($action == 'returns') {
                // TODO 转存idArr
                $idArr = $formData['idArr'] ? $formData['idArr'] : [];

                $result = model('User.User')->onlyTrashed()->whereIn('id', $idArr)->update(['deletetime' => null]);

                $result === FALSE ? $this->error(' 还原失败,') : $this->success('还原成功');
            }

            if ($action == 'return') {
                $userid = $this->request->param('userid', '');

                $user = $this->UserModel->onlyTrashed()->find($userid);

                if (!$user) $this->error('用户不存在');

                $result = $user->restore();

                if ($result === FALSE) $this->error('还原失败,' . model('User.User')->getError());

                $this->success('还原成功', url('admin/user/index'));
            }

            // TODO 删除
            if ($action == 'del') {
                $userid = $this->request->param('userid', '');

                $user = $this->UserModel->find($userid);

                if (!$user) $this->error('用户不存在');

                $result = $this->UserModel->destroy($userid, true);

                if ($result === FALSE) $this->error('删除失败');

                $this->success('删除成功', url('admin/user/index'));
            }

            if ($action == 'dels') {
                // TODO 转存idArr
                $idArr = $formData['idArr'];

                $userList = $this->TypeModel->onlyTrashed()->whereIn('id', $idArr)->select();

                $result = $this->UserModel->destroy($idArr, true);

                if ($result === FALSE) {
                    $this->error('删除失败');
                } else {
                    foreach ($userList as $item) {
                        @is_file('.' . $item['avatar']) && unlink('.' . $item['avatar']);
                        @is_file('.' . $item['cover']) && unlink('.' . $item['cover']);
                    }
                    $this->success('删除成功', url('admin/user/index'));
                }
            }
        }

        $userList = $this->UserModel->onlyTrashed('deletetime')->order('deletetime', 'desc')->paginate(5);

        return $this->fetch('', [
            'navTitle' => $this->navTitle,
            'userList' => $userList
        ]);
    }
}
